// shenfenyanzhen.js
let fn = require('../../utils/Requestutil');

Page({
  data: {
    school: '',
    yuanxi: '',
    username: '',
    studentId: '',
    gender: '',
    entranceYear: '',
    isVerified: false,
  },

  onLoad() {
    const token = wx.getStorageSync('token');
    if (!token) {
      this.showLoginPrompt();
      return;
    }
    this.loadStudentData();
  },

  showLoginPrompt() {
    wx.showToast({ title: '请先登录', icon: 'none', duration: 2000 });
    setTimeout(() => {
      wx.redirectTo({ url: '/pages/login/login' });
    }, 500);
  },

  loadStudentData() {
    const student = wx.getStorageSync('student');
    const verifiedData = wx.getStorageSync('verifiedStudentData')
    console.log('verifiedData:',verifiedData);
    if (student) {
      this.setStudentData(student, true);
    } else if(verifiedData){
      this.setStudentData(verifiedData, true);
    }
  },

  setStudentData(data, isVerified) {
    this.setData({
      school: data.school,
      yuanxi: data.department,
      username: data.name,
      studentId: data.studentId,
      gender: data.gender === 1 ? '男' : '女',
      entranceYear: data.graduationDate,
      isVerified: isVerified
    });
  },

  onInputChange(event) {
    const field = event.currentTarget.dataset.field;
    this.setData({ [field]: event.detail });
  },

  validateFormData() {
    const { school, yuanxi, username, studentId, gender, entranceYear } = this.data;
    if (!school || !yuanxi || !username.trim() || !studentId || !gender || !entranceYear) {
      return '请填写所有必填项';
    }
    if (gender !== '男' && gender !== '女') {
      return '请选择正确的性别';
    }
    if (!/^\d{4}-(0[1-9]|1[0-2])$/.test(entranceYear)) {
      return '毕业年月格式必须是YYYY-MM';
    }
    return null;
  },

  async saveFormData() {
    const errorMsg = this.validateFormData();
    if (errorMsg) {
      wx.showToast({ title: errorMsg, icon: 'none', duration: 2000 });
      return;
    }

    const encryptedopenId = wx.getStorageSync('token');
    if (!encryptedopenId) {
      wx.showToast({ title: '请登录', icon: 'none', duration: 2000 });
      return;
    }

    const { school, yuanxi, username, studentId, gender, entranceYear } = this.data;
    const studentData = {
      school,
      department: yuanxi,
      name: username,
      studentId,
      gender: gender === '男' ? 1 : 0,
      graduationDate: entranceYear
    };

    try {
      const result = await fn.verifyStudent(studentData, encryptedopenId);
      console.log(result);
      if (result.code === 0) {
        wx.showToast({ title: '验证成功', icon: 'success' });
        
        wx.setStorageSync('respondStudent', result.student);
        wx.setStorageSync('verifiedStudentData', studentData);
        wx.navigateBack();
      } else {
        wx.showToast({
           title: '验证失败：' + result.message, 
           icon: 'error' 
          });
      }
    } catch (err) {
      wx.showToast({ title: '请求失败，请稍后重试', icon: 'error' });
      console.log(err);
    }
  }
});
